package com.xaaef.grpc.client;

import com.xaaef.grpc.client.util.GrpcBreaker;
import com.xaaef.grpc.client.util.RestBreaker;
import com.xaaef.grpc.lib.pb.GreeterGrpc;
import com.xaaef.grpc.lib.pb.HelloReply;
import com.xaaef.grpc.lib.pb.HelloRequest;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;


@Slf4j
@RestController
@RequestMapping
public class GrpcClientController {

    private final GreeterGrpc.GreeterBlockingStub greeterService;

    private final FeignProviderService providerService;


    public GrpcClientController(FeignProviderService providerService,
                                @GrpcClient("istio-grpc-server")
                                GreeterGrpc.GreeterBlockingStub greeterService) {
        this.providerService = providerService;
        this.greeterService = greeterService;
    }


    @GetMapping("/grpc/hello")
    public Map<String, String> sayHello1(@RequestParam("name") String name) {
        var result = GrpcBreaker.fallbackWithStatus(
                () -> greeterService.sayHello(
                        HelloRequest.newBuilder().setName(name).build()),
                status -> HelloReply.newBuilder()
                        .putAllMessage(Map.of("message", status.getDescription()))
                        .build()
        );
        return result.getData().getMessageMap();
    }


    @GetMapping("/rest/hello")
    public Map<String, String> sayHello2(@RequestParam("name") String name) {
        var result = RestBreaker.fallbackWithMessage(
                () -> providerService.sayHello(name),
                errorDetails -> Map.of("message", errorDetails)
        );
        return result.getData();
    }


}
